package com.movie.ticket.sale.cinema.assembly.cinemaassembly.apiImpl;



import com.alibaba.csp.ahas.shaded.com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movie.ticket.sale.cinema.assembly.cinemaassembly.common.UpdateUtil;
import com.movie.ticket.sale.cinema.assembly.cinemaassembly.info.*;
import com.movie.ticket.sale.cinema.assembly.cinemaassembly.service.CinemaService;
import com.movie.ticket.sale.cinemaApi.CinemaApi;
import com.movie.ticket.sale.moviecommon.common.Result;
import com.movie.ticket.sale.moviecommon.model.TCinemaMovie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
public class CinemaApiImpl implements CinemaApi , ApplicationRunner {
    @Autowired
    private CinemaService cinemaService;
    @Autowired
    private CinemaApiImpl impl;
    @Autowired
    private UpdateUtil updateUtil;

    public void changeStringToSetStream(String obj) {
        log.info("====={}",obj);
        Map<String, String> map=(Map<String, String>) JSON.parse(obj);
        System.out.println(map.get("a1"));
        System.out.println("======长度为："+map.size());
        for (String s : map.keySet()) {
            System.out.println("键："+s+",值："+map.get(s));
        }


    }

    /**
     * 通过影院id找到相关联的电影票房
     * @return
     */
    @Override
    public Result cinemaAcount() {
        log.info("开始查找电影票房数据");

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));
        List<MovieAcountInfo> movieNames = cinemaService.findMovieNameById(cinemaId);
        if (movieNames.size()<1){
            return Result.success("暂无票房信息");
        }
        return Result.success(movieNames);
    }


    /**
     * 查看影院的订单信息
     * @param currPage
     * @param size
     * @param type ticket/vip  选择查询订单的类型
     * @param tradeNuo 订单号
     * @return
     */
    @Override
    public Result findTicketOrder(int currPage, int size, String type, String tradeNuo) {
        log.info("开始查找订单信息，type为{}",type);
        //获取cinemaId
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        //判断查询vip 订单  还是ticket订单
        if (type.equals("vip")){
//          说明查找的是vip的订单
//          获取分页对象
            Page<VipOrderInfo> pageParm = new Page<>();
            pageParm.setCurrent(currPage);
            pageParm.setSize(size);
            IPage<VipOrderInfo> vipOrder = cinemaService.findVipOrder(pageParm, cinemaId, tradeNuo);
            if (vipOrder.getRecords().size()<1){
                return Result.success("暂无订单信息");
            }
            return Result.success(vipOrder);
        }
        //获取分页对象
        Page<MovieOrderInfo> pageParm = new Page<>();
        pageParm.setCurrent(currPage);
        pageParm.setSize(size);
        IPage<MovieOrderInfo> ticketOrder = cinemaService.findTicketOrder(pageParm, cinemaId, tradeNuo);
        if (ticketOrder.getRecords().size()<1){
            return Result.success("暂无订单信息");
        }
        return Result.success(ticketOrder);
    }


    /**
     * 查看当前影院的运营状态
     * @return
     */
    @Override
    public Result showState() {
        log.info("开始查找当前影院状态");

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        CinemaState cinema = cinemaService.findCinemaStateById(cinemaId);
        int state = cinema.getState();
        if (state==0){

            return Result.success("已申请");
        }else if(state==1){
            return Result.success("人工审核中");
        }else if(state==2){
            return Result.success("正常");
        }else if(state==-1){
            return Result.success("影院已停运");
        }
        return Result.fail(404,"影院不存在");
    }
//====================================影片管理========================================================
    /**
     * 分页查询电影,模糊查询
     * @param currPage
     * @param size
     * @return
     */
    @Override
    public Result findAllMovies(int currPage, int size, String name) {
        log.info("开始分页查找电影，当前页为{}，size为{}",currPage,size);

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        Page<MovieDataInfo> pageParm = new Page<>();
        pageParm.setCurrent(currPage);
        pageParm.setSize(size);
        IPage<MovieDataInfo> allMovies = cinemaService.findAllMovies(pageParm, name);
        return Result.success(allMovies);
    }

    /**
     * 分页查询,模糊查询,查找自己平台的电影
     * @param currPage
     * @param size
     * @param name
     * @return
     */
    @Override
    public Result findCinemaMovie(int currPage, int size, String name) {
        log.info("开始分页查找电影，当前页为{}，size为{}",currPage,size);

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        int chainId = impl.findChainId(cinemaId);

        Page<MovieDataInfo> pageParm = new Page<>();
        pageParm.setCurrent(currPage);
        pageParm.setSize(size);
        IPage<MovieDataInfo> Movies = cinemaService.findCinemaMovie(pageParm, chainId,name);
        return Result.success(Movies);
    }

    /**
     * 将电影关联到影院
     * @param movieId
     * @return
     */
    @Override
    public Result pullMovie(int movieId) {
        log.info("将平台的电影信息拉取到相关院线");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));
        //判断是否存在该排片
        List<CinemaMovieInfo> exist = cinemaService.isExist(movieId, cinemaId);
        if (exist.size()>0){
            return Result.fail(403,"已存在该影片，请勿重复操作");
        }
        if (!impl.isChain(cinemaId)){
            return Result.fail(403,"权限不足");
        }
        TCinemaMovie tm=new TCinemaMovie();
        tm.setCinemaId(cinemaId);
        tm.setMovieId(movieId);
        tm.setState(0);//关联之后 默认是下架的
        cinemaService.pullMovie(tm);
        return Result.success("拉取成功");
    }

    /**
     * 将电影下架
     * @param movieId
     * @return
     */
    @Override
    public Result soldOutCinemaMovie(int movieId) {
        log.info("将平台的电影下架");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(!impl.isChain(cinemaId)){
            return Result.fail(403,"权限不足");
        }
        cinemaService.soldOutCinemaMovie(movieId,cinemaId);
        return Result.success("下架成功");
    }

    /**
     * 将电影上架
     * @param movieId
     * @return
     */
    @Override
    public Result putawayCinemaMovie(int movieId) {
        log.info("将平台的电影上架");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(!impl.isChain(cinemaId)){
            return Result.fail(403,"权限不足");
        }
        cinemaService.putawayCinemaMovie(movieId,cinemaId);
        return Result.success("上架成功");
    }

//====================================影厅管理========================================================

    /**
     * 分页查询影厅，条件-影厅类型
     * @param currPage
     * @param size
     * @param type
     * @return
     */
    @Override
    public Result findAuditorium(int currPage, int size, String type) {
        log.info("开始分页查找影厅，当前页为{}，size为{}，类型为{}",currPage,size,type);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"本账号为管理账号，不具备影厅操作");
        }
        Page<AuditoriumInfo> pageParm = new Page<>();
        pageParm.setCurrent(currPage);
        pageParm.setSize(size);
        IPage<AuditoriumInfo> Movies = cinemaService.findAuditorium(pageParm, cinemaId,type);
        List<AuditoriumInfo> records = Movies.getRecords();
        if (records.size()<1){
            return Result.success("暂无影厅信息");
        }
        return Result.success(Movies);
    }

    /**
     * 新增影厅
     * @param name
     * @param type
     * @param seatCount
     * @param seatStream
     * @return
     */
    @Override
    public Result addAuditorium(String name, String type, int seatCount, String seatStream) {
        log.info("新增影厅，影厅名为{}，类型为{}，座位总数{}，座位信息详情{}",name,type,seatCount,seatStream);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"本账号为管理账号，不具备影厅操作");
        }
        AuditoriumInfo info=new AuditoriumInfo();
        info.setCinemaId(cinemaId);//这里使用登录之后的影院id
        info.setName(name);
        info.setType(type);
        info.setSeatCount(seatCount);
        info.setSeatStream(seatStream);
        info.setState(0);//新增影厅的状态默认为停用状态
        cinemaService.addAuditorium(info);
        return Result.success("新增成功");
    }

    /**
     * 修改影厅信息
     * @param id 影厅id
     * @param name 影厅名
     * @param type 影厅类型
     * @param seatCount 影厅座位总数
     * @param seatStream 影厅座位信息
     * @param state 影厅状态
     * @return
     */
    @Override
    public Result updateAuditorium(int id,String name, String type, int seatCount, String seatStream, int state) {
        log.info("修改影厅，影厅id为{}，影厅名为{}，类型为{}，座位总数{}，座位信息详情{}，状态：{}",id,name,type,seatCount,seatStream,state);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"本账号为管理账号，不具备影厅操作");
        }
        AuditoriumInfo info=new AuditoriumInfo();
        info.setId(id);
        info.setCinemaId(cinemaId);//这里使用登录之后的影院id
        info.setName(name);
        info.setType(type);
        info.setSeatCount(seatCount);
        info.setSeatStream(seatStream);
        info.setState(state);
        cinemaService.updateAuditorium(info);
        return Result.success("修改成功");
    }

//====================================vip管理========================================================
    /**
     * 新增vip规则
     * @param priceVar 决定价格的因子
     * @param tipDiscount 手续费折扣
     * @param ticketDiscount 票价折扣
     * @return
     */
    @Override
    public Result addVip(int priceVar, double tipDiscount, double ticketDiscount) {
        log.info("新增vip规则，价格因子为{}，手续费折扣为{}，票价折扣为{}",priceVar,tipDiscount,ticketDiscount);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(!impl.isChain(cinemaId)){
            return Result.fail(403,"权限不足");
        }
        VipInfo info=new VipInfo();
        info.setCinemaId(cinemaId);//只有院线能设置vip规则
        info.setPriceVar(priceVar);//设置价格因子
        info.setTicketDiscount(ticketDiscount);//设置票价折扣
        info.setTipDiscount(tipDiscount);//设置手续费折扣
        info.setState(0);//设置规则状态，默认为下架状态
        cinemaService.addVip(info);
        return Result.success("添加成功");
    }

    /**
     * 分页查询vip会员规则，一级影院就查自己的id，二级影院查他的上级id
     * @param currPage
     * @param size
     * @param state
     * @return
     */
    @Override
    public Result findVip(int currPage, int size, Integer state) {
        log.info("分页查询vip规则，当前页为{}，每页数量为{}，条件为{}",currPage,size,state);
        Page<VipInfo> page=new Page<>();
        page.setCurrent(currPage);
        page.setSize(size);
        //首先判断当前影院是否是院线,这里的cinemaId为登录状态
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        int bool = cinemaService.findParentCinema(cinemaId);
        if(bool==0){
            //说明是院线，直接使用cinemaId
            IPage<VipInfo> vipRules = cinemaService.findVip(page, cinemaId, state);
            return Result.success(vipRules);
        }
        //没有进入if说明是二级影院,cinemaId使用返回的父级id
        IPage<VipInfo> vipRules = cinemaService.findVip(page, bool, state);

        return Result.success(vipRules);
    }

    /**
     * 修改vip规则
     * @param id 规则id
     * @param priceVar 决定价格的因子
     * @param tipDiscount 手续费折扣
     * @param ticketDiscount 票价折扣
     * @param state vip规则状态
     * @return
     */
    @Override
    public Result updateVip(int id,int priceVar, double tipDiscount, double ticketDiscount, int state) {
        log.info("修改vip规则，id为{}，价格因子为{}，手续费折扣为{}，票价折扣为{}，规则状态为{}",id,priceVar,tipDiscount,ticketDiscount,state);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(!impl.isChain(cinemaId)){
            return Result.fail(403,"权限不足");
        }
        VipInfo info=new VipInfo();
        info.setId(id);
        info.setCinemaId(cinemaId);
        info.setPriceVar(priceVar);
        info.setTipDiscount(tipDiscount);
        info.setTicketDiscount(ticketDiscount);
        info.setState(state);
        cinemaService.updateVip(info);
        return Result.success("修改成功");
    }

    /**
     * 删除vip规则
     * @param id
     * @return
     */
    @Override
    public Result delVip(int id) {
        log.info("删除id为{}的会员规则",id);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(!impl.isChain(cinemaId)){
            return Result.fail(403,"权限不足");
        }
        cinemaService.delVip(id);
        return Result.success("删除成功");
    }

    /**
     * 新增排片
     * @param movieId 选择的电影id
     * @param auditoriumId 选择的影厅id
     * @param startTime 开始时间
     * @param price 票价
     * @return
     */
    @Override
    public Result addPlan(int movieId, int auditoriumId, String startTime, double price) {
        log.info("开始排片，电影id为{}，影厅id为{}，开始时间{}，票价{}",movieId,auditoriumId,startTime,price);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"该账户为管理账户，不能排片");
        }
        //字符串格式的时间 转为 date类型
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newTime = null;
        try {
            newTime = sdf.parse(startTime);
        } catch (ParseException e) {
            return Result.fail(403,"时间格式不正确");
        }


        boolean bool = impl.isTime(newTime);
        if (!bool){
            return Result.fail(403,"时间设置错误，请重新设置时间");
        }
//        首先根据电影id找到电影信息，主要是找到放映的时长，来计算结束时间
        MovieDataInfo movieDataInfo = cinemaService.findMovieById(movieId);
        Date endTime=new Date();//电影结束时间
        endTime.setTime(newTime.getTime()+movieDataInfo.getTime()*60*1000);
        String format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);

        //判断该时间影厅是否被占用
        List<UserInfo> use = cinemaService.isUse(cinemaId, auditoriumId);
        for (UserInfo u:use){

            if (newTime.before(u.getEndTime())&&newTime.after(u.getStartTime()))
                return Result.fail(403,"该时间影厅已存在场次，请重新选择时间或影厅");

            if (endTime.before(u.getEndTime())&&endTime.after(u.getStartTime()))
                return Result.fail(403,"该时间影厅已存在场次，请重新选择时间或影厅");

            if(newTime.equals(u.getStartTime()))
                return Result.fail(403,"该时间影厅已存在场次，请重新选择时间或影厅");

        }


//        接下来根据影厅id找到影厅的相关信息，主要是找到座位的信息
        AuditoriumInfo auditoriumInfo = cinemaService.findAuditoriumById(auditoriumId);
        String seatStream = auditoriumInfo.getSeatStream();
        //增加场次表
        PeridInfo info=new PeridInfo();
        info.setCinemaId(cinemaId);
        info.setAuditoriumId(auditoriumId);
        info.setMovieId(movieId);
        info.setStartTime(startTime);
        info.setEndTime(format1);
        info.setPrice(price);
        info.setSeatStram(seatStream);
        info.setState(2);//设置2为未开始 1为进行中 0为已完成
        cinemaService.addPlan(info);
        //增加座位
        Map<String, String> map=(Map<String, String>) JSON.parse(seatStream);
        System.out.println("======长度为："+map.size());
        for (String s : map.keySet()) {
            System.out.println("键："+s+",值："+map.get(s));
            int state = Integer.parseInt(map.get(s));

        }

        return Result.success("排片成功");
    }

    /**
     * 分页条件查询场次
     * @param currPage 当前页
     * @param size 数量
     * @param state 状态
     * @param auditoriumId 影厅id
     * @param movieId 电影id
     * @return
     */
    @Override
    public Result findPlan(int currPage, int size, Integer state, Integer auditoriumId, Integer movieId) {
        log.info("分页条件查询，当前页{}，数量{}，状态{}，影厅id{}，电影id{}",currPage,size,state,auditoriumId,movieId);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"该账户为管理账户，无排片信息");
        }
        Page<PeridInfo> page=new Page<>();
        page.setCurrent(currPage);
        page.setSize(size);
        IPage<PeridInfo> plan = cinemaService.findPlan(page,cinemaId, state, auditoriumId, movieId);
        List<PeridInfo> records = plan.getRecords();
        if (records.size()<1){
            return Result.success("暂无排片信息");
        }
        return Result.success(plan);
    }

    /**
     * 修改排片信息
     * @param id 场次id
     * @param movieId 电影id
     * @param auditoriumId 影厅id
     * @param startTime 开始时间
     * @param price 票价
     * @return
     */
    @Override
    public Result updatePlan(int id,int movieId, int auditoriumId, String startTime, double price) {
        log.info("修改排片，场次id为{}，电影id为{}，影厅id为{}，开始时间{}，票价{}",id,movieId,auditoriumId,startTime,price);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"该账户为管理账户，无排片信息");
        }
        //字符串格式的时间 转为 date类型
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newTime = null;
        try {
            newTime = sdf.parse(startTime);
        } catch (ParseException e) {
            return Result.fail(403,"时间格式不正确");
        }
        boolean bool = impl.isTime(newTime);
        if (!bool){
            return Result.fail(403,"时间设置错误，请重新设置时间");
        }
        //        首先根据电影id找到电影信息，主要是找到放映的时长，来计算结束时间
        MovieDataInfo movieDataInfo = cinemaService.findMovieById(movieId);
        Date endTime=new Date();//电影结束时间
        endTime.setTime(newTime.getTime()+movieDataInfo.getTime()*60*1000);
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);
        //        接下来根据影厅id找到影厅的相关信息，主要是找到座位的信息
        AuditoriumInfo auditoriumInfo = cinemaService.findAuditoriumById(auditoriumId);
        PeridInfo info=new PeridInfo();
        info.setId(id);
        info.setCinemaId(cinemaId);
        info.setAuditoriumId(auditoriumId);
        info.setStartTime(startTime);
        info.setEndTime(format);
        info.setPrice(price);
        info.setSeatStram(auditoriumInfo.getSeatStream());
        cinemaService.updatePlan(info);
        return Result.success("修改成功");
    }

    /**
     * 定时查询所有未完成场次，根据时间自动修改订单状态
     */
    public void autoUpdatePerid(){
        log.info("自动更新场次信息");
        List<PeridStateInfo> peridState = cinemaService.findPeridState();
        for (PeridStateInfo p: peridState){
            Date startTime = p.getStartTime();
            Date endTime = p.getEndTime();
            boolean startBool=startTime.after(new Date());
            boolean endBool=endTime.after(new Date());
            if (!startBool){
                //已开始
                if(!endBool){
                    //已结束，修改订单为已完成
                    cinemaService.updatePerid(p.getId(),0);
                }else{
                    //还未结束，修改状态为正在进行
                    cinemaService.updatePerid(p.getId(),1);
                }
            }
        }
    }

    /**
     * 设置定时时间
     */
    private void updateTimer(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                autoUpdatePerid();
            }
        },0,60*1000);
        Timer timer2 = new Timer();
        timer2.schedule(new TimerTask() {
            @Override
            public void run() {
                autoUpdateOrder();
            }
        },0,60*1000);
    }

    /**
     * 执行定时任务
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        updateTimer();
    }

    public void autoUpdateOrder(){
        log.info("开始自动更新订单的状态");
        //首先找出所有状态为未完成的订单（也就是状态<7的订单），找出场次id
        List<AutoOrderInfo> allOrders = cinemaService.findAllOrder();
        for (AutoOrderInfo a:allOrders){
            int peridId = a.getPeridId();//获取场次Id
            int i = cinemaService.findperidState(peridId);
            if (i==0){
                //状态i等于0，说明场次已完成，修改订单的状态为7
                cinemaService.finishOrder(a.getId(),7);
                //同时修改票房
                cinemaService.addBoxOffice(a.getMovieId(),a.getTicketPrice());
            }

        }
    }




    /**
     * 根据id删除场次
     * @param id
     * @return
     */
    @Override
    public Result delPlan(int id) {
        log.info("删除id为{}的电影场次");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        if(impl.isChain(cinemaId)){
            return Result.fail(403,"该账户为管理账户，无排片信息");
        }
        cinemaService.delPlan(id);
        return Result.success("删除成功");
    }

    /**
     * 查询影院的年费
     * @return
     */
    @Override
    public Result annualCost() {
        log.info("查询id为{}的影院的年费");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        CinemaInfo cinemaInfo = cinemaService.annualCost(cinemaId);
        return Result.success(cinemaInfo);
    }

    /**
     * 修改影院的信息
     * @param name 影院名
     * @param address 影院地址
     * @param tel 联系电话
     * @param service 支持的服务
     * @param file 影院主页的图片文件
     * @return
     */
    @Override
    public Result updateCinema(String name, String address, String tel, String service, MultipartFile file) {
        log.info("修改影院信息，影院名字{}，地址{}，电话{}，服务{}，文件{}",name,address,tel,service,file);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        //获取cinema_data表的id
        int cinemaDataId = cinemaService.findCinemaDataId(cinemaId, 0);
        //将文件上传到ftp，并将路径返回
        Result result = updateUtil.updateOneFile("cinema", file, cinemaDataId);
        String url = (String) result.getData();
        //修改cinema表的信息
        cinemaService.updateCinemaData(cinemaId,tel,name,address,service);
        //修改cinema_data中的图片路径
        CinemaDataInfo cinemaDataInfo=new CinemaDataInfo();
        cinemaDataInfo.setFilePath(url);//设置图片路径
        cinemaDataInfo.setType(0);//设置类型为0（影院封面）
        cinemaDataInfo.setCinemaId(cinemaId);//设置影院的id
        cinemaService.updateCinemaFilePath(cinemaDataInfo);
        return Result.success("修改成功");
    }


    /**
     * 关闭影院，若是院线，就提示请联系管理员
     * @return
     */
    @Override
    public Result closeCinema() {
        log.info("关闭影院");
        //首先判断是否是院线
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        int cinemaId=Integer.parseInt(request.getHeader("id"));

        int bool = cinemaService.findParentCinema(cinemaId);
        if(bool==0){
            //说明是院线，直接使用cinemaId
            return Result.fail(403,"暂无权限，请联系管理员处理");
        }
        //说明是二级影院，将状态改为停运
        cinemaService.closeCinema(cinemaId);

        return Result.success("已关闭");
    }

    /**
     * 用户取票，状态改为6（已取票）
     * @param checkCode 取票码
     * @return
     */
    @Override
    public Result signIn(String checkCode) {
        log.info("取票码为{}",checkCode);
        //判断取票码是否存在
        List<Integer> signIn = cinemaService.isSignIn(checkCode);
        if (signIn.size()<1)
            return Result.fail(403,"取票码输入错误");

        cinemaService.signIn(checkCode);
        return Result.success("取票成功");
    }


    /**
     * 根据cinemaId找出父级id
     * @param cinemaId
     * @return
     */
    public int findChainId(int cinemaId){
        log.info("找到id为{}的影院账号的院线",cinemaId);
        int chainId = cinemaService.findParentCinema(cinemaId);
        if (chainId==0){
            //如果chain等于0，则该cinemaId就是院线
            return cinemaId;
        }
        //没有进入if，说明isChain就是该cinemaId的父级院线
        return chainId;
    }

    /**
     * 判断该cinemaId是否为院线
     * @param cinemaId
     * @return
     */
    public boolean isChain(int cinemaId){
        log.info("查找id为{}的影院账号是否为院线",cinemaId);
        int isChain = cinemaService.findParentCinema(cinemaId);
        if (isChain==0){
            //如果chain等于0，则该cinemaId就是院线
            return true;
        }
        return false;
    }

    /**
     * 比较时间，传入时间在当前时间之后，返回true
     * @param time
     * @return
     */
    public boolean isTime(Date time){
        log.info("入参为{}",time);
        long l = System.currentTimeMillis();//获取当前时间的long值
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置格式
        Date nowTime= new Date(l);//将long转换为date格式
        System.out.println("nowTime:"+nowTime);
        boolean bool = nowTime.before(time);//如果现在的时间比场次的开始时间早，则为true
        return bool;
    }


}
